#include <STC89C5xRC.H>
#include "timer0.h"
#include "key.h"
#include "delay.h"
#include "nixie.h"
#include "at24c02.h"

unsigned char keynum;
unsigned char min,sec,minisec;//100个minisec等于1s
unsigned char runflag;


void main()
{
	time0_init();
	while(1)
	{
		keynum=key();
		if(keynum==1)
		{
			runflag=!runflag;
		}
		if(keynum==2)
		{
			min=0;
			sec=0;
			minisec=0;
			runflag=0;
		}
		if(keynum==3)
		{
			at24c02_writebyte(0,min);
			Delayms(5);
			at24c02_writebyte(1,sec);
			Delayms(5);
			at24c02_writebyte(2,minisec);
			Delayms(5);
		}
		if(keynum==4)
		{
			min=at24c02_readbyte(0);
			sec=at24c02_readbyte(1);
			minisec=at24c02_readbyte(2);
		}
		nixie_setbuf(1,min/10);
		nixie_setbuf(2,min%10);
		nixie_setbuf(3,17);
		nixie_setbuf(4,sec/10);
		nixie_setbuf(5,sec%10);
		nixie_setbuf(6,17);
		nixie_setbuf(7,minisec/10);
		nixie_setbuf(8,minisec%10);

	}

}

void sec_loop()
{
	if(runflag)
	{
		minisec++;
		if(minisec>=100)
		{
			minisec=0;
			sec++;
			if(sec>=60)
			{
				sec=0;
				min++;
				if(min>=60)
				{
					min=0;
				}
			}
		}
	}
}

//定时器中断函数模板
void timer0_routine() interrupt 1
{
	static unsigned int t0count1,t0count2,t0count3;
	TH0=64535/256;
	TL0=64535%256;
	t0count1++;
	if(t0count1>=20)
	{
		t0count1 = 0;
		key_loop();
	}
	t0count2++;
	if(t0count2>=1)
	{
		t0count2 = 0;
		nixie_loop();
	}
	t0count3++;
	if(t0count3>=10)
	{
		t0count3 = 0;
		sec_loop();
	}
}
